package com.wwj.app.handler;

import com.wwj.core.common.Constants;
import com.wwj.framework.utils.ReturnData;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jsessionId = request.getParameter("jsessionid");
        String playerIdStr = request.getParameter("playerId");
        if(jsessionId == null || jsessionId.isEmpty() || playerIdStr == null || playerIdStr.isEmpty()) {
            outputNeedLogin(response);
            return false;
        }

        Jedis jedis = jedisPool.getResource();
        String cache = jedis.get(jsessionId);
        if(cache == null || cache.isEmpty()) {
            outputNeedLogin(response);
            return false;
        }

        JSONObject json = JSONObject.fromObject(cache);
        if(!json.containsKey("sessionId") || !json.containsKey("userId")) {
            outputNeedLogin(response);
            return false;
        }

        int playerId = Integer.valueOf(playerIdStr);
        if(!json.getString("sessionId").equals(jsessionId)
                || json.getInt("userId") != playerId) {
            outputNeedLogin(response);
            return false;
        }
        jedis.setex(jsessionId, Constants.SESSION_TIME_OUT, json.toString());
        jedis.close();

        return super.preHandle(request, response, handler);
    }

    private void outputNeedLogin(HttpServletResponse response) throws IOException {
        ReturnData returnData = new ReturnData();
        returnData.failure("请登录", String.valueOf(Constants.NEED_LOGIN));
        JSONObject jsonObject = JSONObject.fromObject(returnData);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(jsonObject.toString());
        out.close();
    }
}
